const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema(
  {
    userName: {
      type: String,
    },
    nickName: {
      type: String,
    },
    password: {
      type: String,
    },
    passwordAgain: {
      type: String,
    },
    roles: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "role",
      },
    ],
  },
  {
    timestamps: true, // 这将自动添加 createdAt 和 updatedAt 字段
  }
);

// UserSchema.virtual("formattedCreatedAt").get(function () {
//   return this.createdAt.toLocaleDateString("zh-CN", {
//     year: "numeric",
//     month: "long",
//     day: "numeric",
//   });
// });

UserSchema.statics.paginate = async function (filter = {}, options = {}) {
  const { limit = 10, page = 1 } = options;
  const skip = (page - 1) * limit;
  const count = await this.countDocuments(filter);
  const entity = await this.find(filter)
    .populate("roles")
    .limit(limit)
    .skip(skip);

  return {
    results: entity.map((item) => {
      return {
        ...item.toObject(),
        formattedCreatedAt: item.formattedCreatedAt
     } 
    }),
    count,
    page,
    limit,
  };
};

module.exports = mongoose.model("user", UserSchema);
